3 * This is the Oracle database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\DatabaseDomain
;
27 use Wikimedia\Rdbms\Blob
;
28 use Wikimedia\Rdbms\ResultWrapper
;
29 use Wikimedia\Rdbms\DBConnectionError
;
30 use Wikimedia\Rdbms\DBUnexpectedError
;
31 use Wikimedia\Rdbms\DBExpectedError
;
36 class DatabaseOracle
extends Database
{
38 protected $mLastResult = null;
40 /** @var int The number of rows affected as an integer */
41 protected $mAffectedRows;
44 private $ignoreDupValOnIndex = false;
46 /** @var bool|array */
47 private $sequenceData = null;
49 /** @var string Character set for Oracle database */
50 private $defaultCharset = 'AL32UTF8';
53 private $mFieldInfoCache = [];
55 function __construct( array $p ) {
58 if ( $p['tablePrefix'] == 'get from global' ) {
59 $p['tablePrefix'] = $wgDBprefix;
61 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
62 parent
::__construct( $p );
63 Hooks
::run( 'DatabaseOraclePostInit', [ $this ] );
66 function __destruct() {
67 if ( $this->opened
) {
68 Wikimedia\
suppressWarnings();
70 Wikimedia\restoreWarnings
();
78 function implicitGroupby() {
82 function implicitOrderby() {
86 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
87 global $wgDBOracleDRCP;
89 if ( !function_exists( 'oci_connect' ) ) {
90 throw new DBConnectionError(
92 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
93 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
99 $this->password
= $password;
101 // Backward compatibility (server used to be null and TNS was supplied in dbname)
102 $this->server
= $dbName;
103 $realDatabase = $user;
105 // $server now holds the TNS endpoint
106 $this->server
= $server;
107 // $dbName is schema name if different from username
108 $realDatabase = $dbName ?
: $user;
111 if ( !strlen( $user ) ) { # e.g. the class is being loaded
115 if ( $wgDBOracleDRCP ) {
116 $this->setFlag( DBO_PERSISTENT
);
119 $session_mode = $this->flags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
121 Wikimedia\
suppressWarnings();
122 if ( $this->flags
& DBO_PERSISTENT
) {
123 $this->conn
= oci_pconnect(
127 $this->defaultCharset
,
130 } elseif ( $this->flags
& DBO_DEFAULT
) {
131 $this->conn
= oci_new_connect(
135 $this->defaultCharset
,
139 $this->conn
= oci_connect(
143 $this->defaultCharset
,
147 Wikimedia\restoreWarnings
();
149 if ( $this->user
!= $realDatabase ) {
150 // change current schema in session
151 $this->selectDB( $realDatabase );
153 $this->currentDomain
= new DatabaseDomain(
160 if ( !$this->conn
) {
161 throw new DBConnectionError( $this, $this->lastError() );
164 $this->opened
= true;
166 # removed putenv calls because they interfere with the system globaly
167 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
168 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
169 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
171 return (bool)$this->conn
;
175 * Closes a database connection, if it is open
176 * Returns success, true if already closed
179 protected function closeConnection() {
180 return oci_close( $this->conn
);
183 function execFlags() {
184 return $this->trxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
189 * @return bool|mixed|ORAResult
191 protected function doQuery( $sql ) {
192 wfDebug( "SQL: [$sql]\n" );
193 if ( !StringUtils
::isUtf8( $sql ) ) {
194 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
197 // handle some oracle specifics
198 // remove AS column/table/subquery namings
199 if ( !$this->getFlag( DBO_DDLMODE
) ) {
200 $sql = preg_replace( '/ as /i', ' ', $sql );
203 // Oracle has issues with UNION clause if the statement includes LOB fields
204 // So we do a UNION ALL and then filter the results array with array_unique
205 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
206 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
207 // you have to select data from plan table after explain
208 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
212 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
218 Wikimedia\
suppressWarnings();
220 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
221 if ( $stmt === false ) {
222 $e = oci_error( $this->conn
);
223 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
228 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
229 $e = oci_error( $stmt );
230 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
231 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
237 Wikimedia\restoreWarnings
();
239 if ( $explain_count > 0 ) {
240 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
241 'WHERE statement_id = \'' . $explain_id . '\'' );
242 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
243 return new ORAResult( $this, $stmt, $union_unique );
245 $this->mAffectedRows
= oci_num_rows( $stmt );
251 function queryIgnore( $sql, $fname = '' ) {
252 return $this->query( $sql, $fname, true );
256 * Frees resources associated with the LOB descriptor
257 * @param ResultWrapper|ORAResult $res
259 function freeResult( $res ) {
260 if ( $res instanceof ResultWrapper
) {
268 * @param ResultWrapper|ORAResult $res
271 function fetchObject( $res ) {
272 if ( $res instanceof ResultWrapper
) {
276 return $res->fetchObject();
280 * @param ResultWrapper|ORAResult $res
283 function fetchRow( $res ) {
284 if ( $res instanceof ResultWrapper
) {
288 return $res->fetchRow();
292 * @param ResultWrapper|ORAResult $res
295 function numRows( $res ) {
296 if ( $res instanceof ResultWrapper
) {
300 return $res->numRows();
304 * @param ResultWrapper|ORAResult $res
307 function numFields( $res ) {
308 if ( $res instanceof ResultWrapper
) {
312 return $res->numFields();
315 function fieldName( $stmt, $n ) {
316 return oci_field_name( $stmt, $n );
319 function insertId() {
320 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
321 $row = $this->fetchRow( $res );
322 return is_null( $row[0] ) ?
null : (int)$row[0];
329 function dataSeek( $res, $row ) {
330 if ( $res instanceof ORAResult
) {
333 $res->result
->seek( $row );
337 function lastError() {
338 if ( $this->conn
=== false ) {
341 $e = oci_error( $this->conn
);
344 return $e['message'];
347 function lastErrno() {
348 if ( $this->conn
=== false ) {
351 $e = oci_error( $this->conn
);
357 protected function fetchAffectedRowCount() {
358 return $this->mAffectedRows
;
362 * Returns information about an index
363 * If errors are explicitly ignored, returns NULL on failure
364 * @param string $table
365 * @param string $index
366 * @param string $fname
369 function indexInfo( $table, $index, $fname = __METHOD__
) {
373 function indexUnique( $table, $index, $fname = __METHOD__
) {
377 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
378 if ( !count( $a ) ) {
382 if ( !is_array( $options ) ) {
383 $options = [ $options ];
386 if ( in_array( 'IGNORE', $options ) ) {
387 $this->ignoreDupValOnIndex
= true;
390 if ( !is_array( reset( $a ) ) ) {
394 foreach ( $a as &$row ) {
395 $this->insertOneRow( $table, $row, $fname );
398 if ( in_array( 'IGNORE', $options ) ) {
399 $this->ignoreDupValOnIndex
= false;
405 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
406 $col_info = $this->fieldInfoMulti( $table, $col );
407 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
410 if ( is_numeric( $col ) ) {
415 } elseif ( $includeCol ) {
419 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
423 if ( $val === 'NULL' ) {
427 if ( $val === null ) {
428 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
441 * @param string $table
443 * @param string $fname
445 * @throws DBUnexpectedError
447 private function insertOneRow( $table, $row, $fname ) {
448 $table = $this->tableName( $table );
449 // "INSERT INTO tables (a, b, c)"
450 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
453 // for each value, append ":key"
455 foreach ( $row as $col => &$val ) {
461 if ( $this->isQuotedIdentifier( $val ) ) {
462 $sql .= $this->removeIdentifierQuotes( $val );
465 $sql .= $this->fieldBindStatement( $table, $col, $val );
470 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
471 if ( $stmt === false ) {
472 $e = oci_error( $this->conn
);
473 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
477 foreach ( $row as $col => &$val ) {
478 $col_info = $this->fieldInfoMulti( $table, $col );
479 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
481 if ( $val === null ) {
482 // do nothing ... null was inserted in statement creation
483 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
484 if ( is_object( $val ) ) {
485 $val = $val->fetch();
488 // backward compatibility
489 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
490 $val = $this->getInfinity();
493 $val = MediaWikiServices
::getInstance()->getContentLanguage()->
494 checkTitleEncoding( $val );
495 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
496 $e = oci_error( $stmt );
497 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
502 /** @var OCI_Lob[] $lob */
503 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
504 if ( $lob[$col] === false ) {
505 $e = oci_error( $stmt );
506 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
509 if ( is_object( $val ) ) {
510 $val = $val->fetch();
513 if ( $col_type == 'BLOB' ) {
514 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
515 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
517 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
518 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
523 Wikimedia\
suppressWarnings();
525 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
526 $e = oci_error( $stmt );
527 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
528 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
532 $this->mAffectedRows
= oci_num_rows( $stmt );
535 $this->mAffectedRows
= oci_num_rows( $stmt );
538 Wikimedia\restoreWarnings
();
540 if ( isset( $lob ) ) {
541 foreach ( $lob as $lob_v ) {
546 if ( !$this->trxLevel
) {
547 oci_commit( $this->conn
);
550 return oci_free_statement( $stmt );
553 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
554 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
556 $destTable = $this->tableName( $destTable );
558 $sequenceData = $this->getSequenceData( $destTable );
559 if ( $sequenceData !== false &&
560 !isset( $varMap[$sequenceData['column']] )
562 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
565 // count-alias subselect fields to avoid abigious definition errors
567 foreach ( $varMap as &$val ) {
568 $val .= ' field' . $i;
572 $selectSql = $this->selectSQLText(
574 array_values( $varMap ),
581 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
583 if ( in_array( 'IGNORE', $insertOptions ) ) {
584 $this->ignoreDupValOnIndex
= true;
587 $this->query( $sql, $fname );
589 if ( in_array( 'IGNORE', $insertOptions ) ) {
590 $this->ignoreDupValOnIndex
= false;
594 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
597 if ( $rows === [] ) {
598 return true; // nothing to do
601 if ( !is_array( reset( $rows ) ) ) {
605 $sequenceData = $this->getSequenceData( $table );
606 if ( $sequenceData !== false ) {
607 // add sequence column to each list of columns, when not set
608 foreach ( $rows as &$row ) {
609 if ( !isset( $row[$sequenceData['column']] ) ) {
610 $row[$sequenceData['column']] =
611 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
612 $sequenceData['sequence'] . '\')' );
617 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
620 function tableName( $name, $format = 'quoted' ) {
622 Replace reserved words with better ones
623 Using uppercase because that's the only way Oracle can handle
631 $name = 'PAGECONTENT';
635 return strtoupper( parent
::tableName( $name, $format ) );
638 function tableNameInternal( $name ) {
639 $name = $this->tableName( $name );
641 return preg_replace( '/.*\.(.*)/', '$1', $name );
645 * Return sequence_name if table has a sequence
647 * @param string $table
650 private function getSequenceData( $table ) {
651 if ( $this->sequenceData
== null ) {
652 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
653 lower(atc.table_name),
654 lower(atc.column_name)
655 FROM all_sequences asq, all_tab_columns atc
658 '{$this->tablePrefix}MWUSER',
659 '{$this->tablePrefix}USER',
662 atc.column_name || '_SEQ' = '{$this->tablePrefix}' || asq.sequence_name
663 AND asq.sequence_owner = upper('{$this->getDBname()}')
664 AND atc.owner = upper('{$this->getDBname()}')" );
666 while ( ( $row = $result->fetchRow() ) !== false ) {
667 $this->sequenceData
[$row[1]] = [
668 'sequence' => $row[0],
673 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
675 return $this->sequenceData
[$table] ??
false;
679 * Returns the size of a text field, or -1 for "unlimited"
681 * @param string $table
682 * @param string $field
685 function textFieldSize( $table, $field ) {
686 $fieldInfoData = $this->fieldInfo( $table, $field );
688 return $fieldInfoData->maxLength();
691 function limitResult( $sql, $limit, $offset = false ) {
692 if ( $offset === false ) {
696 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
699 function encodeBlob( $b ) {
700 return new Blob( $b );
703 function decodeBlob( $b ) {
704 if ( $b instanceof Blob
) {
711 function unionQueries( $sqls, $all ) {
712 $glue = ' UNION ALL ';
714 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
715 'FROM (' . implode( $glue, $sqls ) . ')';
718 function wasDeadlock() {
719 return $this->lastErrno() == 'OCI-00060';
722 function duplicateTableStructure( $oldName, $newName, $temporary = false,
725 $temporary = $temporary ?
'TRUE' : 'FALSE';
727 $newName = strtoupper( $newName );
728 $oldName = strtoupper( $oldName );
730 $tabName = substr( $newName, strlen( $this->tablePrefix
) );
731 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
732 $newPrefix = strtoupper( $this->tablePrefix
);
734 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
735 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
738 function listTables( $prefix = null, $fname = __METHOD__
) {
740 if ( !empty( $prefix ) ) {
741 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
744 $owner = strtoupper( $this->getDBname() );
745 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
746 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
748 // dirty code ... i know
750 $endArray[] = strtoupper( $prefix . 'MWUSER' );
751 $endArray[] = strtoupper( $prefix . 'PAGE' );
752 $endArray[] = strtoupper( $prefix . 'IMAGE' );
753 $fixedOrderTabs = $endArray;
754 while ( ( $row = $result->fetchRow() ) !== false ) {
755 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
756 $endArray[] = $row['table_name'];
763 public function dropTable( $tableName, $fName = __METHOD__
) {
764 $tableName = $this->tableName( $tableName );
765 if ( !$this->tableExists( $tableName ) ) {
769 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
772 function timestamp( $ts = 0 ) {
773 return wfTimestamp( TS_ORACLE
, $ts );
777 * Return aggregated value function call
779 * @param array $valuedata
780 * @param string $valuename
783 public function aggregateValue( $valuedata, $valuename = 'value' ) {
788 * @return string Wikitext of a link to the server software's web site
790 public function getSoftwareLink() {
791 return '[{{int:version-db-oracle-url}} Oracle]';
795 * @return string Version information from the database
797 function getServerVersion() {
798 // better version number, fallback on driver
799 $rset = $this->doQuery(
800 'SELECT version FROM product_component_version ' .
801 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
803 $row = $rset->fetchRow();
805 return oci_server_version( $this->conn
);
808 return $row['version'];
812 * Query whether a given index exists
813 * @param string $table
814 * @param string $index
815 * @param string $fname
818 function indexExists( $table, $index, $fname = __METHOD__
) {
819 $table = $this->tableName( $table );
820 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
821 $index = strtoupper( $index );
822 $owner = strtoupper( $this->getDBname() );
823 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
824 $res = $this->doQuery( $sql );
826 $count = $res->numRows();
836 * Query whether a given table exists (in the given schema, or the default mw one if not given)
837 * @param string $table
838 * @param string $fname
841 function tableExists( $table, $fname = __METHOD__
) {
842 $table = $this->tableName( $table );
843 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
844 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
845 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
846 $res = $this->doQuery( $sql );
847 if ( $res && $res->numRows() > 0 ) {
859 * Function translates mysql_fetch_field() functionality on ORACLE.
860 * Caching is present for reducing query time.
861 * For internal calls. Use fieldInfo for normal usage.
862 * Returns false if the field doesn't exist
864 * @param array|string $table
865 * @param string $field
866 * @return ORAField|ORAResult|false
868 private function fieldInfoMulti( $table, $field ) {
869 $field = strtoupper( $field );
870 if ( is_array( $table ) ) {
871 $table = array_map( [ $this, 'tableNameInternal' ], $table );
872 $tableWhere = 'IN (';
873 foreach ( $table as &$singleTable ) {
874 $singleTable = $this->removeIdentifierQuotes( $singleTable );
875 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
876 return $this->mFieldInfoCache
["$singleTable.$field"];
878 $tableWhere .= '\'' . $singleTable . '\',';
880 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
882 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
883 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
884 return $this->mFieldInfoCache
["$table.$field"];
886 $tableWhere = '= \'' . $table . '\'';
889 $fieldInfoStmt = oci_parse(
891 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
892 $tableWhere . ' and column_name = \'' . $field . '\''
894 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
895 $e = oci_error( $fieldInfoStmt );
896 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
900 $res = new ORAResult( $this, $fieldInfoStmt );
901 if ( $res->numRows() == 0 ) {
902 if ( is_array( $table ) ) {
903 foreach ( $table as &$singleTable ) {
904 $this->mFieldInfoCache
["$singleTable.$field"] = false;
907 $this->mFieldInfoCache
["$table.$field"] = false;
909 $fieldInfoTemp = null;
911 $fieldInfoTemp = new ORAField( $res->fetchRow() );
912 $table = $fieldInfoTemp->tableName();
913 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
917 return $fieldInfoTemp;
921 * @throws DBUnexpectedError
922 * @param string $table
923 * @param string $field
926 function fieldInfo( $table, $field ) {
927 if ( is_array( $table ) ) {
928 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
931 return $this->fieldInfoMulti( $table, $field );
934 protected function doBegin( $fname = __METHOD__
) {
936 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
939 protected function doCommit( $fname = __METHOD__
) {
940 if ( $this->trxLevel
) {
941 $ret = oci_commit( $this->conn
);
943 throw new DBUnexpectedError( $this, $this->lastError() );
946 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
950 protected function doRollback( $fname = __METHOD__
) {
951 if ( $this->trxLevel
) {
952 oci_rollback( $this->conn
);
954 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
958 function sourceStream(
960 callable
$lineCallback = null,
961 callable
$resultCallback = null,
962 $fname = __METHOD__
, callable
$inputCallback = null
966 $dollarquote = false;
969 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
970 while ( !feof( $fp ) ) {
971 if ( $lineCallback ) {
972 call_user_func( $lineCallback );
974 $line = trim( fgets( $fp, 1024 ) );
975 $sl = strlen( $line ) - 1;
980 if ( $line[0] == '-' && $line[1] == '-' ) {
984 // Allow dollar quoting for function declarations
985 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
986 if ( $dollarquote ) {
987 $dollarquote = false;
988 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
993 } elseif ( !$dollarquote ) {
994 if ( $line[$sl] == ';' && ( $sl < 2 ||
$line[$sl - 1] != ';' ) ) {
996 $line = substr( $line, 0, $sl );
1006 $cmd = str_replace( ';;', ";", $cmd );
1007 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1008 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1009 $replacements[$defines[2]] = $defines[1];
1012 foreach ( $replacements as $mwVar => $scVar ) {
1013 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1016 $cmd = $this->replaceVars( $cmd );
1017 if ( $inputCallback ) {
1018 call_user_func( $inputCallback, $cmd );
1020 $res = $this->doQuery( $cmd );
1021 if ( $resultCallback ) {
1022 call_user_func( $resultCallback, $res, $this );
1025 if ( $res === false ) {
1026 $err = $this->lastError();
1028 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1040 protected function doSelectDomain( DatabaseDomain
$domain ) {
1041 if ( $domain->getSchema() !== null ) {
1042 // We use the *database* aspect of $domain for schema, not the domain schema
1043 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
1046 $database = $domain->getDatabase();
1047 if ( $database === null ||
$database === $this->user
) {
1048 // Backward compatibility
1049 $this->currentDomain
= $domain;
1054 // https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj32268.html
1055 $encDatabase = $this->addIdentifierQuotes( strtoupper( $database ) );
1056 $sql = "ALTER SESSION SET CURRENT_SCHEMA=$encDatabase";
1057 $stmt = oci_parse( $this->conn
, $sql );
1058 Wikimedia\
suppressWarnings();
1059 $success = oci_execute( $stmt );
1060 Wikimedia\restoreWarnings
();
1062 // Update that domain fields on success (no exception thrown)
1063 $this->currentDomain
= $domain;
1065 $e = oci_error( $stmt );
1066 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1072 function strencode( $s ) {
1073 return str_replace( "'", "''", $s );
1076 function addQuotes( $s ) {
1077 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1078 if ( isset( $contLang->mLoaded
) && $contLang->mLoaded
) {
1079 $s = $contLang->checkTitleEncoding( $s );
1082 return "'" . $this->strencode( $s ) . "'";
1085 public function addIdentifierQuotes( $s ) {
1086 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1093 public function removeIdentifierQuotes( $s ) {
1094 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1097 public function isQuotedIdentifier( $s ) {
1098 return strpos( $s, '/*Q*/' ) !== false;
1101 private function wrapFieldForWhere( $table, &$col, &$val ) {
1102 $col_info = $this->fieldInfoMulti( $table, $col );
1103 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1104 if ( $col_type == 'CLOB' ) {
1105 $col = 'TO_CHAR(' . $col . ')';
1107 MediaWikiServices
::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1108 } elseif ( $col_type == 'VARCHAR2' ) {
1110 MediaWikiServices
::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1114 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1116 foreach ( $conds as $col => $val ) {
1117 if ( is_array( $val ) ) {
1118 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1120 if ( is_numeric( $col ) && $parentCol != null ) {
1121 $this->wrapFieldForWhere( $table, $parentCol, $val );
1123 $this->wrapFieldForWhere( $table, $col, $val );
1125 $conds2[$col] = $val;
1132 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1133 $options = [], $join_conds = []
1135 if ( is_array( $conds ) ) {
1136 $conds = $this->wrapConditionsForWhere( $table, $conds );
1139 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1143 * Returns an optional USE INDEX clause to go after the table, and a
1144 * string to go at the end of the query
1146 * @param array $options An associative array of options to be turned into
1147 * an SQL query, valid keys are listed in the function.
1150 function makeSelectOptions( $options ) {
1151 $preLimitTail = $postLimitTail = '';
1155 foreach ( $options as $key => $option ) {
1156 if ( is_numeric( $key ) ) {
1157 $noKeyOptions[$option] = true;
1161 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1163 $preLimitTail .= $this->makeOrderBy( $options );
1165 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1166 $postLimitTail .= ' FOR UPDATE';
1169 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1170 $startOpts .= 'DISTINCT';
1173 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1174 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1179 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1180 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1185 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1188 public function delete( $table, $conds, $fname = __METHOD__
) {
1189 global $wgActorTableSchemaMigrationStage;
1191 if ( is_array( $conds ) ) {
1192 $conds = $this->wrapConditionsForWhere( $table, $conds );
1194 // a hack for deleting pages, users and images (which have non-nullable FKs)
1195 // all deletions on these tables have transactions so final failure rollbacks these updates
1196 // @todo: Normalize the schema to match MySQL, no special FKs and such
1197 $table = $this->tableName( $table );
1198 if ( $table == $this->tableName( 'user' ) &&
1199 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
)
1201 $this->update( 'archive', [ 'ar_user' => 0 ],
1202 [ 'ar_user' => $conds['user_id'] ], $fname );
1203 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1204 [ 'ipb_user' => $conds['user_id'] ], $fname );
1205 $this->update( 'image', [ 'img_user' => 0 ],
1206 [ 'img_user' => $conds['user_id'] ], $fname );
1207 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1208 [ 'oi_user' => $conds['user_id'] ], $fname );
1209 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1210 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1211 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1212 [ 'fa_user' => $conds['user_id'] ], $fname );
1213 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1214 [ 'us_user' => $conds['user_id'] ], $fname );
1215 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1216 [ 'rc_user' => $conds['user_id'] ], $fname );
1217 $this->update( 'logging', [ 'log_user' => 0 ],
1218 [ 'log_user' => $conds['user_id'] ], $fname );
1219 } elseif ( $table == $this->tableName( 'image' ) ) {
1220 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1221 [ 'oi_name' => $conds['img_name'] ], $fname );
1224 return parent
::delete( $table, $conds, $fname );
1228 * @param string $table
1229 * @param array $values
1230 * @param array $conds
1231 * @param string $fname
1232 * @param array $options
1234 * @throws DBUnexpectedError
1236 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1237 $table = $this->tableName( $table );
1238 $opts = $this->makeUpdateOptions( $options );
1239 $sql = "UPDATE $opts $table SET ";
1242 foreach ( $values as $col => &$val ) {
1243 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1246 $sqlSet = ', ' . $sqlSet;
1253 if ( $conds !== [] && $conds !== '*' ) {
1254 $conds = $this->wrapConditionsForWhere( $table, $conds );
1255 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1258 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1259 if ( $stmt === false ) {
1260 $e = oci_error( $this->conn
);
1261 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1265 foreach ( $values as $col => &$val ) {
1266 $col_info = $this->fieldInfoMulti( $table, $col );
1267 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1269 if ( $val === null ) {
1270 // do nothing ... null was inserted in statement creation
1271 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1272 if ( is_object( $val ) ) {
1273 $val = $val->getData();
1276 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1277 $val = '31-12-2030 12:00:00.000000';
1280 $val = MediaWikiServices
::getInstance()->getContentLanguage()->
1281 checkTitleEncoding( $val );
1282 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1283 $e = oci_error( $stmt );
1284 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1289 /** @var OCI_Lob[] $lob */
1290 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1291 if ( $lob[$col] === false ) {
1292 $e = oci_error( $stmt );
1293 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1296 if ( is_object( $val ) ) {
1297 $val = $val->getData();
1300 if ( $col_type == 'BLOB' ) {
1301 $lob[$col]->writeTemporary( $val );
1302 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1304 $lob[$col]->writeTemporary( $val );
1305 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1310 Wikimedia\
suppressWarnings();
1312 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1313 $e = oci_error( $stmt );
1314 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1315 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1319 $this->mAffectedRows
= oci_num_rows( $stmt );
1322 $this->mAffectedRows
= oci_num_rows( $stmt );
1325 Wikimedia\restoreWarnings
();
1327 if ( isset( $lob ) ) {
1328 foreach ( $lob as $lob_v ) {
1333 if ( !$this->trxLevel
) {
1334 oci_commit( $this->conn
);
1337 return oci_free_statement( $stmt );
1340 function bitNot( $field ) {
1341 // expecting bit-fields smaller than 4bytes
1342 return 'BITNOT(' . $field . ')';
1345 function bitAnd( $fieldLeft, $fieldRight ) {
1346 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1349 function bitOr( $fieldLeft, $fieldRight ) {
1350 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1353 function getServer() {
1354 return $this->server
;
1357 public function buildGroupConcatField(
1358 $delim, $table, $field, $conds = '', $join_conds = []
1360 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1362 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1365 public function buildSubstring( $input, $startPosition, $length = null ) {
1366 $this->assertBuildSubstringParams( $startPosition, $length );
1367 $params = [ $input, $startPosition ];
1368 if ( $length !== null ) {
1369 $params[] = $length;
1371 return 'SUBSTR(' . implode( ',', $params ) . ')';
1375 * @param string $field Field or column to cast
1379 public function buildStringCast( $field ) {
1380 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1383 public function getInfinity() {
1384 return '31-12-2030 12:00:00.000000';